#!/usr/bin/env python3

from pymodbus.server import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext

# 创建数据存储区 (默认初始化为0)
store = ModbusSlaveContext(
    di=ModbusSequentialDataBlock(0, [0]*100),  # 离散输入
    co=ModbusSequentialDataBlock(0, [0]*100),  # 线圈
    hr=ModbusSequentialDataBlock(0, [0]*100),  # 保持寄存器
    ir=ModbusSequentialDataBlock(0, [0]*100)   # 输入寄存器
)

context = ModbusServerContext(slaves=store, single=True)

# 设备标识
identity = ModbusDeviceIdentification()
identity.VendorName = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/riptideio/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Pymodbus Server'

# 启动服务器 - 使用非特权端口 5020
if __name__ == "__main__":
    print("Starting Modbus TCP Server...")
    print("Listening on localhost:5020")
    StartTcpServer(context=context, identity=identity, address=("127.0.0.1", 5020))